import { getWsClient } from '@/getClient';
import { MsgConnectFailed } from '@/shared/protocols/AMessages/Test/MsgConnectFailed';
import { users } from '@/shared/types/user';
import { RTCConnection } from '@/utils/RTCConnection';
import mitt from "@/mitt";
import { ref, reactive, onMounted, onUnmounted,watch, computed, watchEffect, nextTick } from 'vue';
/*
 * @Date: 2023-02-24 19:44:38
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-02-26 21:32:28
 * @FilePath: \A19\frontend\src\hooks\test\watcherhook.ts
 */
export function watcherhook(currentUser:users,testId:string) {
  const wsClient = getWsClient();
  const rtcConnections = reactive(new Map<string, RTCConnection>());
  // const stuConnections = new Map()

  //连接失败
  wsClient.listenMsg(/^AMessages\/Test\//, (call, msgName) => {
    if (msgName === "AMessages/Test/ConnectFailed") {
      //考试不存在
      ElMessage.warning((call as MsgConnectFailed).message);
    }
  });
  //教师进入考场，服务器下发目前考场学生信息
  wsClient.listenMsg("AMessages/Test/StudentStatus", (call) => {
    students.push(...call.students);
  });
  //& 学生加入离开考试
  wsClient.listenMsg("AMessages/Test/ConnectInfo", (call) => {
    if (call.info === "connected") {
      students.push(call.student);
    } else {
      const i = students.findIndex(
        (student) => student._id === call.student._id
      );
      students.splice(i, 1);

      rtcConnections.delete(call.student._id);
      console.log(rtcConnections);
    }
  });
  //监听握手msg
  wsClient.listenMsg("AMessages/RTC/RTCConn", (msg) => {
    const origin = msg.origin;
    if (msg.type === "video-offer") {
      const rtcConnection = new RTCConnection(
        wsClient,
        currentUser._id,
        "test",
        testId
      );
      rtcConnections.set(origin, rtcConnection);
      // console.log(rtcConnections);
      rtcConnection.handleVideoOffer(msg);
    } else if (msg.type === "new-ice-candidate") {
      const rtcConnection = rtcConnections.get(origin);
      if (rtcConnection === undefined) {
        throw Error("origin ==> rtcConnection unexist!");
      }
      rtcConnection.addCandidate(msg);
    }
  });

  const videoRef = ref(new Array<HTMLVideoElement>());

  const students = reactive(new Array<users>());
  const page = ref(1)
  const amount = ref(6)
  const currentRTCs = ref<RTCConnection[]>(new Array)
  const condition = ref('')
  const theCondition = ref('')
  const find = ()=>{
    theCondition.value = condition.value
  }
  watchEffect(() =>{
    const allRtcs = [...rtcConnections.values()].filter((rtc,index,arr) => {
      const reg = new RegExp(theCondition.value)
      if(theCondition.value){
        return reg.test(students[index].name) || reg.test(students[index].number)
      }
      
      return true
    })
    const rtcs = allRtcs.slice((page.value - 1) * amount.value,page.value * amount.value)
    currentRTCs.value = rtcs
    console.log("new rtcs");
    nextTick(() =>{
      console.log("nextTick");
      rtcs.forEach(rtc =>{
        if(rtc.streams[0]){
          const video = videoRef.value.find((video) => {
            return video.id === rtc.target;
          });
          if(video?.srcObject) return
          else{
            if (video) video.srcObject = rtc.streams[0];
          }
        }
        else{
          return
        }
      })
    })
  })

  onMounted(async () => {
    // await client.callApi("Create/CreateTest", {
    //   name: "期末考试",
    //   startTime: new Date(),
    //   endTime: new Date(),
    //   questions: [],
    //   course: "63c0c09ae58ff204b7dcceaa",
    // });
    const v = await wsClient.connect();
    if (!v.isSucc) {
      ElMessage.error(v.errMsg);
      return 0;
    }

    await wsClient.sendMsg("AMessages/Test/TeacherJoin", {
      testId: testId,
      teacher: currentUser._id,
    });

    mitt.on("trackReady", (value) => {
      const rtcConnection = rtcConnections.get(value as string);
      if (rtcConnection === undefined) return;

      const video = videoRef.value.find((video) => {
        return video.id === rtcConnection.target;
      });
      console.log(video);
      console.log(rtcConnection.streams[0].getVideoTracks()[0].getConstraints());
      
      if (video) video.srcObject = rtcConnection.streams[0];
      video?.removeEventListener('fullscreenchange',fullscreenchange)
      video?.addEventListener('fullscreenchange',fullscreenchange)
    });
  });
  const fullscreenchange = (e:Event)=>{
    console.log(e);
  }
  onUnmounted(() => {
    wsClient.disconnect();
    rtcConnections.forEach((rtc) => {
      rtc.closeConnection();
    });
    rtcConnections.clear();

    mitt.off("trackReady");
  });

  return {
    students,
    wsClient,
    videoRef,
    page,
    amount,
    currentRTCs,
    condition,
    find
  };
}
